package com.pad.app;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

public class MainActivity extends Activity {

    private TextView mTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_main);

        mTextView = findViewById(R.id.text_view);

        updateTextView();

        findViewById(R.id.btn_refresh).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                updateTextView();
            }
        });

        IntentFilter filter = new IntentFilter();
        filter.addAction("android.dynamic.ACTION_KEY_EVENT");
        filter.addAction("android.dynamic.ACTION_SHUTDOWN_THREAD");
        registerReceiver(mReceiver, filter);

        requestPermissions(new String[]{Manifest.permission.CAMERA}, 0);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_VOLUME_UP:
                updateTextView();
                break;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                updateTextView();
                break;
        }
        return super.onKeyUp(keyCode, event);
    }

    private void updateTextView() {
        WindowManager wm = getSystemService(WindowManager.class);
        DisplayMetrics outMetrics = new DisplayMetrics();
        Configuration cfg = getResources().getConfiguration();
        wm.getDefaultDisplay().getRealMetrics(outMetrics);
        StringBuilder builder = new StringBuilder();
        builder.append("Value : ").append(readFile());
        builder.append("Density : ").append(outMetrics.density).append("\n");
        builder.append("Pixels : ").append(outMetrics.widthPixels).append("x").append(outMetrics.heightPixels).append("\n");
        builder.append("densityDpi : ").append(cfg.densityDpi).append("\n");
        builder.append("smallestScreenWidthDp : ").append(cfg.smallestScreenWidthDp).append("\n");
        builder.append("uiMode : ").append(cfg.uiMode).append("\n");
        builder.append("orientation : ").append(cfg.orientation).append("\n");
        builder.append("screenWidthDp : ").append(cfg.screenWidthDp).append("\n");
        builder.append("screenHeightDp : ").append(cfg.screenHeightDp).append("\n");
        builder.append("fontScale : ").append(cfg.fontScale).append("\n");
        builder.append("Time : ").append(System.currentTimeMillis());
        builder.append("\n\nCamera:\r").append(getCameraSize());
        mTextView.setText(builder.toString());
    }

    private void writeFile(String value) {
        try {
            FileWriter fileWriter = new FileWriter("/sys/bus/platform/devices/gpio_ctrl/otg");
            fileWriter.write(value);
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "Write (" + value + ") -> " + e, Toast.LENGTH_LONG).show();
        }
    }

    private String readFile() {
        char[] cbuf = new char[32];
        try {
            FileReader fileReader = new FileReader("/sys/bus/platform/devices/gpio_ctrl/otg");
            int len = fileReader.read(cbuf);
            if (len > 0) {
                return new String(cbuf, 0, len);
            }
            fileReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            //Log.w("wss", "receiver : " +action);
            if ("android.dynamic.ACTION_KEY_EVENT".equals(action)) { // 此处的Action字段需要跟注册时的对应
                KeyEvent event = intent.getParcelableExtra("key_event");
                switch (event.getKeyCode()) {
                    case KeyEvent.KEYCODE_F10: // 橙色按键（PTT）
                    case KeyEvent.KEYCODE_F11: // F1
                    case KeyEvent.KEYCODE_F12: // F2
                    case KeyEvent.KEYCODE_POWER:
                        Toast.makeText(context, KeyEvent.keyCodeToString(event.getKeyCode()) + ", " + event.getAction(), Toast.LENGTH_SHORT).show();
                        if (KeyEvent.ACTION_DOWN == event.getAction()) {
                            //TODO: 按键按下
                        } else {
                            //TODO: 按键抬起
                        }
                        break;
                }
            } else if ("android.dynamic.ACTION_SHUTDOWN_THREAD".equals(action)) {
                String reason = intent.getStringExtra("reason");
                if ("shutdown".equals(reason)) {
                    // 用户点击了关机按钮
                } else if ("reboot".equals(reason)) {
                    // 用户点击了重启按钮
                }
                Log.e("wss", "reason=" + reason);
                Toast.makeText(context, "Action : " + reason, Toast.LENGTH_SHORT).show();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        int i = 0;
                        for (; ; i++) {
                            Log.e("wss", "hello-->" + i);
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }).start();
            }
        }
    };


    private String getCameraSize() {
        int num = Camera.getNumberOfCameras();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < num; i++) {
            if (i == 0) {
                sb.append("Back Camera:\n");
            } else if (i == 1) {
                sb.append("Front Camera:\n");
            }
            Camera camera = null;
            try {
                camera = Camera.open(i);
                List<Camera.Size> sizes = camera.getParameters().getSupportedPictureSizes();

                for (int m = 0; m < sizes.size(); m++) {
                    Camera.Size size = sizes.get(m);
                    sb.append(size.width + "x" + size.height).append("  ");
                    if ((1 + m) % 3 == 0) sb.append("\n");
                    if (m == sizes.size() - 1) {
                        sb.append("\n");
                    }
                }

                sb.append("\nPreview:\n");
                sizes = camera.getParameters().getSupportedPreviewSizes();

                for (int m = 0; m < sizes.size(); m++) {
                    Camera.Size size = sizes.get(m);
                    sb.append(size.width + "x" + size.height).append("  ");
                    if ((1 + m) % 3 == 0) sb.append("\n");
                    if (m == sizes.size() - 1) {
                        sb.append("\n");
                    }
                }
            } catch (Exception e) {
                sb.append("Camera can not connected!");
                e.printStackTrace();
            } finally {
                if (camera != null)
                    camera.release();
            }
        }
        return sb.toString();
    }
}